package com.itjiange.reglg.exception;

import com.itjiange.reglg.common.BaseResponse;
import com.itjiange.reglg.common.ErrorCode;
import com.itjiange.reglg.utils.ResultUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.HandlerExceptionResolver;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 全局异常处理
 *
 * @author ItJiange
 * @date 2023/11/13
 */
@RestControllerAdvice
@Slf4j
public class GloableExceptionHandler {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public BaseResponse<?> validExceptionHandler(MethodArgumentNotValidException me) {
        List<FieldError> errors = me.getBindingResult().getFieldErrors();
        List<String> collected = errors.stream().map(o -> o.getDefaultMessage())
                .collect(Collectors.toList());
        return ResultUtils.error(ErrorCode.PARAMS_ERROR, collected.toString());
    }

    @ExceptionHandler(BindException.class)
    public BaseResponse<?> validExceptionHandler(BindException e) {
        List<FieldError> errors = e.getBindingResult().getFieldErrors();
        List<String> collected = errors.stream().map(o -> o.getDefaultMessage())
                .collect(Collectors.toList());
        return ResultUtils.error(ErrorCode.PARAMS_ERROR, collected.toString());
    }

    @ExceptionHandler(BussinessException.class)
    public BaseResponse<?> bussinessExceptionHandler(BussinessException e) {
        log.error("BussinessException: {}", e.getMessage());
        return ResultUtils.error(e.getCode(), e.getMessage());
    }

    @ExceptionHandler(RuntimeException.class)
    public BaseResponse<?> runtimeExceptionHandler(RuntimeException e) {
        log.error("RuntimeException: {}", e.getMessage());
        return ResultUtils.error(ErrorCode.SYSTEM_ERROR, e.getMessage());
    }
}
